package edu.qichen.onlineBlog.framework.config;

import edu.qichen.onlineBlog.framework.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.Executors;

/**
 * 功能:拦截器
 * 作者:程序员欧阳子韩
 * 日期:2024/4/7 9:54
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    /**
     * 解决跨域
     *
     * @param registry -
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOriginPatterns("*")
//                .allowedOrigins("*")
                .allowCredentials(true);
    }

    /**
     * 配置拦截器，拦截路径
     * 每次请求到拦截的路径，就会去执行拦截器中的方法
     *
     * @param registry -
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jewInterceptor())
                .addPathPatterns("/**") // 拦截所有路径
                .excludePathPatterns("/user/login",
                        "/user/register",
                        "/email/code",
                        "/swagger-ui/**"); // 排除这些具体路径
    }

    /**
     * 异步请求配置
     *
     * @param configurer -
     */
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(3)));
        configurer.setDefaultTimeout(3 * 10000);
    }

    /**
     * 全局只有一个实例
     *
     * @return -
     */
    @Bean
    public HandlerInterceptor jewInterceptor() {
        return new JwtInterceptor(); //JwtInterceptor是拦截器实现类
    }
}
